import json

from flask import Blueprint, request
from flask_cors import *

from apps.model.execute import home_user_select, role_id_select, menu_select, homepage_detail_select

menu_bp = Blueprint('menu', __name__, url_prefix='/menu')


@menu_bp.route('homepage_detail', methods=['POST', 'GET'])
@cross_origin()
def homepage_detail():
    if request.method == 'GET':
        user_id = request.args.get('user_id')
        user = home_user_select(user_id)
        if user:
            data_list = []
            # 根据user_id查询菜单
            menu = homepage_detail_select(user_id)
            if menu:
                for menu_line in menu:
                    data_dirt = {}
                    dirt = {'title_wgj': str(menu_line[3]), 'name1': str(menu_line[0]), 'name2': str(menu_line[1]),
                            'nPath': menu_line[2], 'nodeId': menu_line[4]}
                    data_dirt.update(dirt)
                    data_list.append(data_dirt)
                str_data = {'code': 200, 'data': data_list}
                json_data = json.dumps(str_data, ensure_ascii=False)
                return json_data
            else:
                data = json.dumps({'code': 400, 'message': 'get menu filed', 'user_id': user_id})
                return data
        else:
            role_id = role_id_select(user_id)
            if role_id:
                data_list = []
                menu = menu_select(role_id)
                if menu:
                    for menu_line in menu:
                        data_dirt = {}
                        dirt = {'title_wgj': str(menu_line[3]), 'name1': str(menu_line[0]), 'name2': str(menu_line[1]),
                                'nPath': menu_line[2], 'nodeId': menu_line[4]}
                        data_dirt.update(dirt)
                        data_list.append(data_dirt)
                    str_data = {'code': 200, 'data': data_list}
                    json_data = json.dumps(str_data, ensure_ascii=False)
                    return json_data
                else:
                    data = json.dumps({'code': 400, 'message': 'get menu filed', 'user_id': user_id})
                    return data
            else:
                data = json.dumps({'code': 400, 'message': 'get user filed', 'user_id': user_id})
                return data
    else:
        data = json.dumps({'code': 400, 'message': 'Do not POST...'})
        return data
